﻿using RabbitMQ_Service.MessageTypes;
using System;
using System.Collections.Generic;
using System.Threading;
using Utility.Global.DataTypes;
using Utility.RabbitMQ_Service;
using Utility.RabbitMQ_Service.Implementations;
using Utility.RabbitMQ_Service.MessageTypes;

namespace Manufacturing_Planning_System_Server
{
    internal class StartAndStopListener
    {
        private StartAndStopListener() { }

        public static StartAndStopListener NewStartAndStopListener()
        {
            return new StartAndStopListener();
        }

        public void StartListener()
        {
            Console.WriteLine("StartAndStop-Listener wurde gestartet.");

            IDictionary<String, Thread> runningThreads = new Dictionary<String, Thread>();

            using (RabbitMQService service = RabbitMQServiceImpl.CreateRabbitMQService())
            {
                using (RabbitMQQueue<StartOrStopMessage> queue = service.NewRabbitMQQueue<StartOrStopMessage>("monitor.startorstop"))
                {   
                    try
                    {
                        while (true)
                        {
                            StartOrStopMessage startOrStop = queue.Receive();
                            String systemName = startOrStop.SystemName;
                            if (startOrStop.Start)
                            {
                                if (!runningThreads.ContainsKey(systemName))
                                {
                                    RunningMPS system = RunningMPS.NewRunningMPS(startOrStop.SystemName);
                                    Thread systemThread = new Thread(new ThreadStart(system.StartSystem));
                                    systemThread.Start();
                                    runningThreads.Add(systemName, systemThread);
                                }
                            }
                            else
                            {
                                Thread systemThread;
                                if (runningThreads.TryGetValue(systemName, out systemThread))
                                {
                                    systemThread.Interrupt();
                                    runningThreads.Remove(systemName);
                                }
                            }
                        }
                    }
                    catch (ThreadInterruptedException)
                    {
                        Console.WriteLine("StartAndStop-Listener wurde beendet.");
                    }
                }
            }
        }
    }
}
